import { Dep } from "./dep.mjs";
import { observe } from "./observe.mjs";

export function defineReactive(obj, key, val) {
    const dep = new Dep()
    let ob = observe(val);
    Object.defineProperty(obj, key, {
        enumerable: true,
        configurable: true,
        get() {
            if (ob) {
                ob.dep.depend();
                if (Array.isArray(val)) {
                    dependArray(val);
                }
            }
            dep.depend();
            return val;
        },
        set(newVal) {
            if (newVal !== val) {
                val = newVal;
                ob = observe(val);
            }
            dep.notify();
        }
    })
}

function dependArray(arr) {
    for (const item of arr) {
        if (item.__ob__) {
            item.__ob__.dep.depend();
        }
        if (Array.isArray(item)) {
            dependArray(item);
        }
    }
}